from flask import Flask, render_template, request, send_from_directory, jsonify
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
import random
import time
import json
import redis
from gevent import pywsgi
import os


def get_remote_address():
    """
    :return: the ip address for the current request (or 127.0.0.1 if none found)
    """
    return request.headers.get("X-Real-IP")


ser = Flask(__name__)
ser.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024
limiter = Limiter(
    ser,
    key_func=get_remote_address,
    default_limits=['50 per second']
)
conn = redis.Redis()
basedir = '/home/ubuntu/celebrate-card-generator'
# ALLOWED_EXTENSIONS = {'png', 'png', 'png', 'png', 'gif', 'GIF'}


# def allowed_file(filename):
#     return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


# hello world! 完成
@ser.route('/')
def index_page():
    # val = conn.get('visitor_total').decode('utf-8')
    # print('val:' + str(val))
    # print(request.headers.get("X-Real-IP"))
    return render_template("index.html", input_text='', res_text='')


@ser.route('/page1.html')
def tmp_page():
    return render_template("page1.html", input_text='', res_text='')


@ser.route('/page2.html')
def pre_page():
    # val = conn.get('visitor_total').decode('utf-8')
    # print('val:' + str(val))
    return render_template("page2.html", input_text='', res_text='')


# 上传图片
@ser.route('/up_picture', methods=['POST'], strict_slashes=False)
def upload_picture():
    # print('up_picture begin')
    file_dir = os.path.join(basedir, 'pictures')
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)
    f = request.files['image']
    # print('f yes')
    if f:
        fname = f.filename
        # print(fname)
        # ext = fname.rsplit('.', 1)[1]
        ext = 'png'
        # writer = request.form['writer']
        # receiver = request.form['receiver']
        # card_num = request.form['cardNum']
        # new_filename = writer + '_' + receiver + '_' + str(time.time()) + '.' + ext
        new_filename = fname + '_' + str(time.time()) + '.' + ext
        # print(new_filename)
        f.save(os.path.join(file_dir, new_filename))
        print('create file: ' + new_filename)
        res = dict()
        res['msg'] = "上传成功"
        res['file_name'] = new_filename
        return jsonify(res)
    else:
        print('fail')
        res = dict()
        res["error"] = 1001
        res["msg"] = "上传失败"
        return jsonify(res)


# 上传图片（上传文字，图片在后端生成）
@ser.route('/up_picture_data', methods=['POST'], strict_slashes=False)
def upload_picture_data():
    # 文件路径
    file_dir = os.path.join(basedir, 'pictures')
    # 判断路径是否存在
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)
    # 读取post过来的数据
    writer = request.form['writer']
    receiver = request.form['receiver']
    content = request.form['content']
    card_num = request.form['cardNum']
    # print(writer)
    # print(receiver)
    # print(content)
    # print(card_num)
    # 生成新的文件名
    new_filename = writer + '_' + receiver + '_' + str(time.time()) + '.png'
    # print(new_filename)
    # 生成redis中要存的数据
    redis_dict = dict()
    redis_dict['writer'] = writer
    redis_dict['receiver'] = receiver
    redis_dict['content'] = content
    redis_dict['cardNum'] = card_num
    redis_context = json.dumps(redis_dict)
    # print(redis_context)
    # 存进redis
    conn.set('citem_' + new_filename, redis_context)
    print('create item: ' + 'citem_' + new_filename)
    # 计数
    # 先处理总的访问人次
    conn.incr('visitor_total')
    # print(conn.get('visitor_total').decode('utf-8'))
    # 再处理各个贺卡的访问人次
    if conn.get('cardNum_' + str(card_num)) is None:
        conn.set('cardNum_' + str(card_num), 1)
        # print(conn.get('cardNum_' + str(card_num)).decode('utf-8'))
    else:
        conn.incr('cardNum_' + str(card_num))
        # print(conn.get('cardNum_' + str(card_num)).decode('utf-8'))
    # 返回
    res = dict()
    res['msg'] = "上传成功"
    res['file_name'] = new_filename
    return new_filename


# 记录人次的接口
# @ser.route('/count', methods=['POST'], strict_slashes=False)
# def count_test():
#     # print('begin')
#     card_num = request.form['cardNum']
#     # 先处理总的访问人次
#     conn.incr('visitor_total')
#     # print(conn.get('visitor_total').decode('utf-8'))
#     # 再处理各个图片的访问人次
#     if conn.get('cardNum_' + str(card_num)) is None:
#         conn.set('cardNum_' + str(card_num), 1)
#         # print(conn.get('cardNum_' + str(card_num)).decode('utf-8'))
#     else:
#         conn.incr('cardNum_' + str(card_num))
#         # print(conn.get('cardNum_' + str(card_num)).decode('utf-8'))
#     dict_res = dict()
#     dict_res['visitor_total'] = conn.get('visitor_total').decode('utf-8')
#     dict_res[card_num] = conn.get('cardNum_' + str(card_num)).decode('utf-8')
#     print('visitor_total:' + str(conn.get('visitor_total')))
#     print('card_num:' + str(card_num) + ' num:' + str(conn.get('cardNum_' + str(card_num))))
#     return jsonify(dict_res)


# 查看某个贺卡使用的人次
@ser.route("/get_card_times", methods=['POST'], strict_slashes=False)
def get_card_times():
    card_num = request.form['cardNum']
    if conn.get('cardNum_' + str(card_num)) is None:
        conn.set('cardNum_' + str(card_num), 0)
    res = dict()
    res['cardNum'] = card_num
    res['num'] = conn.get('cardNum_' + str(card_num)).decode('utf-8')
    return jsonify(res)


# 查看总人次
@ser.route("/get_number_of_visitors", methods=['GET', 'POST'], strict_slashes=False)
def get_number_of_visitors():
    if conn.get('visitor_total') is None:
        conn.set('visitor_total', 0)
    res = dict()
    res['visitor_total'] = conn.get('visitor_total').decode('utf-8')
    return jsonify(res)


# 获取随机字段 完成
def get_noncestr(randomlength):
    random_str = ''
    base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
    length = len(base_str) - 1
    for i in range(randomlength):
        random_str += base_str[random.randint(0, length)]
    return random_str


if __name__ == '__main__':
    if conn.get('visitor_total') is None:
        conn.set('visitor_total', 0)
    # print(conn.get('visitor_total'))
    # server = pywsgi.WSGIServer(('0.0.0.0', 80), ser)
    # server.serve_forever()
    # ser.run(host='0.0.0.0', port=80)
    ser.run(host='0.0.0.0', port=443, ssl_context=('duanzihao.top.pem', 'duanzihao.top.key'))
